package cn.tp.ksoft.civil_driver.view.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by zhusong on 16/4/21.
 * 
 */
public class CircleImageView extends ImageView {

    private final RectF rect = new RectF();
    private final Paint maskPaint = new Paint();
    private final Paint zonePaint = new Paint();

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
 
    public CircleImageView(Context context) {
        super(context);
        init();
    }

    private void init() {
        maskPaint.setAntiAlias(true);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        zonePaint.setAntiAlias(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int minValue = Math.min(getMeasuredHeight(), getMeasuredWidth());
        setMeasuredDimension(minValue, minValue);
        rect.set(0, 0, minValue, minValue);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.save();
        // save before layers
        canvas.saveLayer(rect, zonePaint, Canvas.ALL_SAVE_FLAG);
        // draw circle layer
        final float cx = rect.width() / 2;
        final float cy = rect.height() / 2;
        final float radius = Math.min(cx, cy);
        canvas.drawCircle(cx, cy, radius, zonePaint);
        // mask layer, and get src bound
        canvas.saveLayer(rect, maskPaint, Canvas.ALL_SAVE_FLAG);

        super.draw(canvas);
        canvas.restore();
    }

}